"""Field

 [...], [attr, attr_type]
"""
import re

from jinja2 import Template

from models import items
from templates.hal import HEAD, TEMPLATE, SAMPLE_TEMPLATE


def codegen():
    regex4docs = re.compile('(\s*\|.*)$', re.M)
    
    template = Template(TEMPLATE)
    
    codes = [HEAD]
    
    for item in items:
        title = item['title']
        classname = item['classname']
        tablename = item['tablename']
        columns = [row.split('|')[0].split() for row in item['columns'].split('\n') if row]
    
        docs = regex4docs.sub('', item['columns'])
        if 'docs' in item:
            docs += item['docs']
        docs = docs.replace('\n', '\n{}'.format(' '*4))
    
        attrs = []
        for row in columns:
            attr = None
            if row[1].lower() != row[1]:
                attr = "attr='%s'" % row[1].lower()
    
            attr_type = None
            if row[2].lower() in ('datetime', 'time'):
                attr_type = 'attr_type=halogen.types.ISOUTCDateTime()'
            elif row[2].lower() in ('date',):
                attr_type = 'attr_type=halogen.types.ISOUTCDate()'
    
            attrs.append((attr, attr_type))
    
        code = template.render(title=title,
                               docs=docs,
                               classname=classname,
                               columns=list(zip(columns, attrs)),
                               tablename=tablename)
        codes.append(code)
    
    with open('gen/hal.py', 'w') as f:
        for s in codes:
            f.write(s)


def samplegen():
    template = Template(SAMPLE_TEMPLATE)
    
    samples = [
        'import datetime\n'
    ]
    
    for item in items:
        classname = item['classname']
        columns = [row.split('|')[0].split() for row in item['columns'].split('\n') if row]
        d = template.render(classname=classname, columns=columns)
        samples.append(d)
    
    with open('gen/samples.py', 'w') as f:
        for s in samples:
            f.write(s)


if __name__ == '__main__':
    codegen()
    samplegen()
